package com.qumap.map;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.maps.client.base.Point;
import com.google.gwt.maps.client.base.Size;
import com.google.gwt.maps.client.overlay.HasMarker;
import com.google.gwt.maps.client.overlay.HasMarkerImage;
import com.google.gwt.maps.client.overlay.MarkerImage;
import com.qumap.item.ItemInfo;
import com.qumap.item.ItemOnMap;
import com.qumap.item.info.ImageContainer;
import com.qumap.item.info.MarkerImageInfo;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 23.06.11
 * Time: 21:26
 * To change this template use File | Settings | File Templates.
 */
public class MarkerIconHolder {

    private class MarkerIconSet {
        public HasMarkerImage icon;
        public HasMarkerImage shadow;

    }

    private ItemInfo info;
    private MarkerIconSet[] registered_containers = new MarkerIconSet[Byte.MAX_VALUE];

    public MarkerIconHolder(ItemInfo info) {
        this.info = info;
    }

    public void setImageToMarker(ItemOnMap container, HasMarker marker) {
        ImageContainer image_container = info.getContainerByContent(container.getContent());
        MarkerIconSet set = getMarkerIconSet(image_container);

        marker.setIcon(set.icon);
        setShadow(marker.getJso(), set.shadow.getJso());
    }

    private native void setShadow(JavaScriptObject marker, JavaScriptObject shadow_image) /*-{
        marker.setShadow(shadow_image);
    }-*/;



    private MarkerIconSet getMarkerIconSet(ImageContainer image_container) {
        MarkerIconSet set = registered_containers[image_container.getId()];
        if(set == null) {
            set = registerNewMarkerIconSet(image_container);
        }
        return set;
    }

    private MarkerIconSet registerNewMarkerIconSet(ImageContainer container) {
        MarkerIconSet new_set = new MarkerIconSet();
        new_set.icon = createImage(container.getIconInfo());
        new_set.shadow = createImage(container.getShadowInfo());
        registered_containers[container.getId()] = new_set;
        return new_set;
    }

    private HasMarkerImage createImage(MarkerImageInfo info) {
        MarkerImage.Builder  builder = new MarkerImage.Builder(info.getImageURL());
        builder.setAnchor(new Point(info.getAnchorX(), info.getAnchorY()));
        builder.setOrigin(new Point(info.getOrignX(),info.getOrignY()));
        builder.setSize(new Size(info.getSizeX(), info.getSizeY()));
        return builder.build();
    }

}
